package org.example.zuoye.service.impl;

import org.example.zuoye.service.UploadFileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @Author xinchen
 * @Date: 2024/08/12/ 19:39
 * @Description 图片上传业务
 */
@Service
public class UploadFileServiceImpl implements UploadFileService {

    // 文件上传路径
    @Value("${upload.location}")
    private String uploadFileLocation;
    // 文件访问前缀
    @Value("${upload.server.prefix}")
    private String uploadServerPrefix;

    @Override
    public String uploadAvatar(MultipartFile file) {
        // 获取上传的文件的原文件名
        String fileName = file.getOriginalFilename();
        int dotIndex = fileName.lastIndexOf(".");
        // 取得扩展名
        String ext = fileName.substring(dotIndex);

        // 生成一个新的文件名，以时间命名
        fileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + ext;

        File dir = new File(uploadFileLocation + "/images/avatar/");
        if (!dir.exists()) {
            dir.mkdirs(); // 创建文件夹
        }

        try {
            //目标文件
            File dest = new File(dir.getCanonicalPath() + "/" + fileName);
            //将整个文件传输到目标文件
            file.transferTo(dest);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        System.out.println(fileName);

        return uploadServerPrefix + "images/avatar/" + fileName;
    }
}
